package com.easychat.websocket.netty;

import com.easychat.entity.config.ExecutorConfig;
import com.easychat.entity.dto.TokenUserInfoDTO;
import com.easychat.exception.BusinessException;
import com.easychat.redis.RedisComponent;
import com.easychat.utils.StringTools;
import com.easychat.websocket.ChannelContextUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.DefaultAttributeMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Sharable
 * 标识同一个ChannelHandler的实例可以被多次添加到多个ChannelPipelines中，而且不会出现竞争条件。
 * 如果一个ChannelHandler没有标志@Shareable，在添加到到一个pipeline中时，你需要每次都创建一个新的handler实例，因为它的成员变量是不可分享的。
 */
@Component
@ChannelHandler.Sharable
//@Slf4j
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Logger logger = LoggerFactory.getLogger(HandlerWebSocket.class);

    @Resource
    private RedisComponent redisComponent;
    @Resource
    private ChannelContextUtils channelContextUtils;

    /**
     * 处理接收到的消息
     * @param ctx
     * @param textWebSocketFrame
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //通过channel的唯一id获取对应的userId
        //通过channelContextUtils.addContext(tokenUserInfoDTO.getUserId(), ctx.channel())已经建立了二者联系
        Channel channel = ctx.channel();
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        String userId = attribute.get();
        //logger.info("收到消息：{}，来自用户：{}", textWebSocketFrame.text(), userId);
        //在读到消息时保存心跳
        redisComponent.saveUserHeartBeat(userId);
        //将userId和对应的端口号保存起来，方便消息推送时正确路由，找到联系人所在服务器对应的（mq）channel
        redisComponent.saveServerPort(userId);
        //演示内容
//        //将收到的消息发送给群组
//        channelContextUtils.send2Group(textWebSocketFrame.text());
    }

    /**
     * 连接channel建立成功后，触发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        logger.info("有新的连接加入...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("有连接断开...");
        channelContextUtils.removeContext(ctx.channel());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            //注意这里的执行顺序，是在AccountController的登录方法之后执行
            WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            //获取Uri
            String uri = complete.requestUri();
            //uri = /ws?token=123
            //log.info("uri = {}", uri);
            //获取token
            String token = getToken(uri);
            if (token == null) {
                ctx.channel().close();
                return;
            }
            //log.info("token = {}", token);
            //根据token对应的key在redis中获取tokenUserInfoDTO
            TokenUserInfoDTO tokenUserInfoDTO = redisComponent.getTokenUserInfoDTO(token);
            if (tokenUserInfoDTO == null) {
                ctx.channel().close();
                return;
            }
            //log.info("已通过token获取到对应的tokenUserInfoDTO：{}", tokenUserInfoDTO.toString());
            //要知道是哪个用户建立的连接，以及心跳属于哪个用户，需要将channel和userId对应起来
            //建立channel和userId的联系(将userId和channel绑定起来)
            channelContextUtils.addContext(tokenUserInfoDTO.getUserId(), ctx.channel());
        }
    }

    private String getToken(String uri) {
        if (StringTools.isEmpty(uri) || !uri.contains("?")) {
            return null;
        }
        //通过问号分割 uri = /ws?token=123
        String[] params = uri.split("\\?");//注意转义
        if (params.length != 2) {
            return null;
        }
        //params[1] = "token=123"
        String[] tokenParams = params[1].split("=");
        if (tokenParams.length != 2) {
            return null;
        }
        //tokenParams[1] = "123"
        return tokenParams[1];
    }
}
